import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/pages/subpackage/subpackage_vm.dart';
import 'package:flutter_give/repository/api.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import '../../common_ui/dialog/dialog_factory.dart';
import '../../common_ui/dialog/dialog_title.dart';
import '../../tgpage/binding/qrcode.dart';
import '../Home/home_page.dart';

/// 设备分享页面
class ShareminiPage extends StatefulWidget {
  // 主键id
  final String deviceId;
  final String fromPage; // 新增参数

  const ShareminiPage({super.key, required this.deviceId, this.fromPage = ""});

  @override
  State<StatefulWidget> createState() {
    return ShareminiPageState();
  }
}

class ShareminiPageState extends State<ShareminiPage> {
  // 获取类
  SubpackModel viewModel = SubpackModel();

  static final GlobalKey<HomePageState> globalKeyshare =
      GlobalKey<HomePageState>();

  late String _deviceId;
  late String _fromPage;

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId;
    _fromPage = widget.fromPage;

    LogUtils.w("主键ID: $_deviceId");
    viewModel.getSharedataList(ID: _deviceId);

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff),
      statusBarIconBrightness: Brightness.dark,
    ));
  }

  // 重新加载
  void reloadData() {
    // 在这里实现重新加载数据的逻辑
    print("==============重新加载=============");
    viewModel.getSharedataList(ID: _deviceId);
  }

  Future<bool> _onWillPop() async {
    if (_fromPage == "specificPage") {
      // 判断是否是从特定页面跳转过来的
      LogUtils.w("用户点击了返回按钮，并且是从特定页面跳转过来的");
      HomePageState.globalKeytwo.currentState?.reloadData();
    } else {
      LogUtils.w("用户点击了返回按钮，但不是从特定页面跳转过来的");
    }

    return true;
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (context) => viewModel,
        child: WillPopScope(
          child: Scaffold(
            appBar: AppBar(
              leading: IconButton(
                icon: Icon(Icons.arrow_back_ios),
                onPressed: () {
                  _onWillPop();
                  Navigator.of(context).pop();
                },
              ),
              automaticallyImplyLeading: false,
              title: Text(
                "分享",
                style: TextStyle(
                  fontSize: 17,
                  fontFamily: "PingFang SC",
                  fontWeight: FontWeight.w600,
                ),
              ),
              centerTitle: true,
              actions: [
                TextButton(
                  child: Text(
                    "添加",
                    style: TextStyle(
                      color: Colors.green,
                      fontSize: 16,
                      fontFamily: "PingFang SC",
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  onPressed: () {
                    DialogInputFactory.instancess.showshareDialog(context,_deviceId,
                        onComplete: (success, message) {
                      if (success) {
                        print("操作成功: $message");
                        showToast("分享成功");
                        viewModel.getSharedataList(ID: _deviceId);
                      } else {
                        print("操作失败: $message");
                      }
                    });
                  },
                ),
              ],
            ),
            body: Container(
              color: Color(0xFFF2F3F5),
              child: SafeArea(
                child: Consumer<SubpackModel>(builder: (context,vm,child) {
                  return ListView.builder(
                    itemCount: vm.sharelist?.length ?? 0,
                    itemBuilder: (context, index) {
                      return InkWell(
                        onTap: () {
                          print("点击了第 ${index + 1} 项");
                        },
                        child: Container(
                          margin: EdgeInsets.symmetric(
                              vertical: 8.0, horizontal: 16.0),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10),
                            border: Border.all(color: Colors.white, width: 1.0),
                          ),
                          child: Padding(
                            padding: EdgeInsets.only(
                              top: 10.0,
                              bottom: 10.0,
                              left: 18.0,
                              right: 5,
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text("${vm.sharelist?[index].loginName}"),
                                IconButton(
                                  icon: Icon(Icons.delete),
                                  onPressed: () {
                                    DialogFactory.instance
                                        .showNeedsharedataDialog(
                                      context: context,
                                      dismissClick: () {
                                        //是否显示更新红点
                                        // viewModel.shouldShowUpdateDot();
                                      },
                                      confirmClick: () async {
                                        bool swtich = await Api.instance.getdeleteshare(ID: _deviceId,UserId: "${vm.sharelist?[index].employeeId}");
                                        if (swtich) {
                                          showToast("删除成功");
                                          viewModel.getSharedataList(ID: _deviceId);
                                        } else {
                                          showToast("删除失败");
                                        }
                                      },
                                    );
                                  },
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  );
                }),
              ),
            ),
          ),
          onWillPop: _onWillPop,
        ));
  }
}
